﻿using Nop.Core.Configuration;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Payments;
using Nop.Services.Orders;
using Nop.Services.Tasks;
using System;
using System.Collections.Generic;
using Nop.Services.Logging;

namespace Nop.Web.Services.Task
{
    public class OrderCanacelTask : IScheduleTask
    {
        private readonly NopConfig _config;
        private readonly IOrderService _orderService;
        private readonly IOrderProcessingService _orderProcessingService;
        private readonly ILogger _logger;

        public OrderCanacelTask(ILogger logger, IOrderService orderService, IOrderProcessingService orderProcessingService, NopConfig config)
        {
            _orderService = orderService;
            _orderProcessingService = orderProcessingService;
            _config = config;
            _logger = logger;
        }

        public void Execute()
        {
            try
            {
                var orders = _orderService.SearchOrders(osIds: new List<int>() {
                        (int)OrderStatus.Pending
                    }, psIds: new List<int>() {
                         (int)PaymentStatus.Pending
                    }, createdToUtc: DateTime.Now.ToUniversalTime().AddHours(_config.PaymentTimeOutHours));
                foreach (var order in orders)
                {
                    if (_orderProcessingService.CanCancelOrder(order))
                    {
                        order.OrderNotes.Add(new OrderNote()
                        {
                            Note = $"支付超时取消订单",
                            DisplayToCustomer = true,
                            CreatedOnUtc = DateTime.UtcNow
                        });
                        _orderProcessingService.CancelOrder(order, true);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"取消订单发生错误", ex);

            }
        }
    }
}
